/*
+--------------------------
| FreeloaderOS v0.0.1
|  - Microkernel
+--------------------------
| Written by Alec Hussey
| Copyright (c) 2007
|  - Deus X Foundation
+---------------------------
*/

#include "kernel.h"

void k_main()
{
	k_clear_screen();
	
	k_printf("Freeloader OS v0.0.1\n\n", 0);
	k_update_cursor(1, 0);
	
	k_printf("w00t! I have successfully made my owner kernel!~ LOL!", 3);
	k_update_cursor(5, 0);
};

void k_clear_screen()
{
	char *video_memory = (char*) 0xb8000;
	unsigned int i = 0;
	
	while (i < (80*2*25))
	{
		video_memory[i] = ' ';
		i++;
		video_memory[i] = WHITE_TEXT;
		i++;
	};
};

unsigned int k_printf(char *message, unsigned int line)
{
	char *video_memory = (char*) 0xb8000;
	unsigned int i = 0;
	
	i = (line*80*2);
	
	while (*message != 0)
	{
		if (*message == '\n')
		{
			line++;
			i = (line*80*2);
			*message++;
		}
		else
		{
			video_memory[i] = *message;
			*message++;
			i++;
			video_memory[i] = WHITE_TEXT;
			i++;
		};
	};
	
	return(1);
};

inline void k_outportb(unsigned int port, unsigned char value)
{
    asm volatile("outb %%al,%%dx"::"d" (port), "a" (value));
};

void k_update_cursor(int row, int col)
{
	USHORT position = (row*80) + col;
	
	// cursor LOW port to vga INDEX register
	k_outportb(0x3D4, 0x0F);
	k_outportb(0x3D5, (UCHAR)(position&0xFF));
	
	// cursor HIGH port to vga INDEX register
	k_outportb(0x3D4, 0x0E);
	k_outportb(0x3D5, (UCHAR)((position>>8)&0xFF));
}

unsigned int k_panic(char *message)
{
	char *video_memory = (char*) 0xb8000;
	unsigned int i = 0;
	unsigned int line = 0;

	i = (line*80*2);

	while (*message != 0)
	{
		if (*message == 0x2F)
		{
			*message++;
			if (*message == 0x6e)
			{
				line++;
				i = (line*80*2);
				*message++;
				if (*message == 0)
					return(1);
			};
		};
		video_memory[i] = *message;
		*message++;
		i++;
		video_memory[i] = BLUE_TEXT;
		i++;
	};
	
	return(1);
};
